package com.example.service.impl;

import com.example.dao.CartDao;
import com.example.dao.GoodsDao;
import com.example.dao.MemberDao;
import com.example.entity.Cart;
import com.example.entity.Goods;
import com.example.service.CartService;
import com.example.util.Savesession;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * 购物车服务实现类
 */
@Service
public class CartServiceImpl implements CartService {

    @Resource
    private CartDao cartDao;
    
    @Resource
    private MemberDao memberDao;
    
    @Resource
    private GoodsDao goodsDao;
    
    @Resource
    private Savesession savesession;

    @Override
    public PageInfo<Cart> getCartList(Integer pageNum, Integer pageSize, String key, Integer memberid, Integer goodsid) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", key);
        if (memberid != null) {
            map.put("memberid", memberid);
        }
        if (goodsid != null) {
            map.put("goodsid", goodsid);
        }
        
        PageHelper.startPage(pageNum, pageSize);
        List<Cart> list = cartDao.selectAll(map);
        
        // 处理每个购物车项
        for (Cart cart : list) {
            Goods goods = goodsDao.findById(cart.getGoodsid());
            cart.setGoodsname(goods.getName());
            cart.setGoods(goods);
            
            // 计算价格小计
            Double price = 0.0;
            if (goods.getTjprice() > 0) {
                price = goods.getTjprice();
            } else {
                price = goods.getPrice();
            }
            Double heji = price * cart.getSlnum();
            cart.setHeji(heji);
            
            // 获取库存数量
            int kcnum = savesession.getInventory(goods.getId(), null);
            cart.setKcnum(kcnum);
        }
        
        return new PageInfo<>(list);
    }

    @Override
    public void addCart(Cart cart) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("memberid", cart.getMemberid());
        map.put("goodsid", cart.getGoodsid());
        
        List<Cart> list = cartDao.selectAll(map);
        if (list != null && list.size() > 0) {
            // 如果购物车中已有该商品，则更新数量
            Cart existingCart = list.get(0);
            existingCart.setSlnum(existingCart.getSlnum() + cart.getSlnum());
            cartDao.update(existingCart);
        } else {
            // 否则添加新的购物车项
            cartDao.add(cart);
        }
    }

    @Override
    public void updateCart(Cart cart) {
        cartDao.update(cart);
    }

    @Override
    public void deleteCart(int id) {
        cartDao.delete(id);
    }
} 